﻿using Hangfire;
using lingopen.Application;
using lingopen.Application.System;
using lingopen.Application.System.Implements;
using lingopen.AutoMapper;
using lingopen.Jabil.Server.Core;
using lingopen.Jabil.Server.Swagger;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;

namespace lingopen.Jabil.Server
{
    public class Startup
    {


        IHostingEnvironment _env;
        //public Startup(IConfiguration configuration)
        //{
        //    Configuration = configuration;
        //}
        /// <summary>
        /// Redis 服务
        /// </summary>
        public static ConnectionMultiplexer Redis;
        public Startup(IHostingEnvironment env)
        {
            this._env = env;

            var builder = new ConfigurationBuilder()
                      .SetBasePath(env.ContentRootPath)
                      .AddJsonFile(Path.Combine("configs", "appsettings.json"), optional: true, reloadOnChange: true)  // Settings for the application
                      .AddJsonFile(Path.Combine("configs", $"appsettings.{env.EnvironmentName}.json"), optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables();                                              // override settings with environment variables set in compose.   

            //if (env.IsDevelopment())
            //{
            //    // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
            //    builder.AddUserSecrets();
            //}

            Configuration = builder.Build();
            Globals.Configuration = Configuration;



          //  Redis = ConnectionMultiplexer.Connect(Globals.Configuration["redis"]);
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.RegisterAppServicesFromDirectory(AppContext.BaseDirectory); /* 注册应用服务 */

            /* 缓存 */
            services.AddMemoryCache();

            services.AddSession();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v2", new Info
                {
                    //Title = "智客迅PMS对接平台",
                    Version = "2.5",
                    //TermsOfService = "None",
                    //Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "富士康", Email = "xlingopen@126.com", Url = "http://www.zhikexun.com" },
                    //License = new Swashbuckle.AspNetCore.Swagger.License { Name = "富士康©" + DateTime.Now.ToString("yyyy"), Url = "http://www.zhikexun.com" },
                });
                c.DescribeAllEnumsAsStrings();
                c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数 
                c.MapType<byte[]>(() => new Swashbuckle.AspNetCore.Swagger.Schema
                {
                    Type = null
                });
                c.DocInclusionPredicate((docName, description) => true);
                c.DocumentFilter<DynamicApiDocumentFilter>(); //定义controller名称 
                //var xmlPath = Path.Combine(AppContext.BaseDirectory, "Docs.xml");
                //c.IncludeXmlComments(xmlPath); // 注意：此处替换成所生成的XML documentation的文件名。
            });
            services.ConfigureSwaggerGen(c =>
            {
                var xmlFilePaths = new List<string>() {
                    "BLE.xml",
                    //"Demo.Web.xml"
                    //...
                    //添加自己需要显示注释的的XML
                };
                foreach (var filePath in xmlFilePaths)
                {
                    var xmlFilePath = Path.Combine(AppContext.BaseDirectory, filePath);
                    if (File.Exists(xmlFilePath))
                    {
                        c.IncludeXmlComments(xmlFilePath);
                    }
                }
            });
            ////注入Hangfire服务
            //services.AddHangfire(config => config.UseRedisStorage(Redis));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            Globals.ServiceProvider = app.ApplicationServices;

            AceMapper.InitializeMap();//初始化 AutoMapper
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseSession();
            app.UseCookiePolicy();
            //string ip = Globals.Configuration["tcp:ip"];
            //int port = Convert.ToInt32(Globals.Configuration["tcp:port"]);
            // server.Start(ip, port);
            

            //app.UseHangfireServer();
            //app.UseHangfireDashboard("/hangfire");

            //var filter = new BasicAuthAuthorizationFilter(
            // new BasicAuthAuthorizationFilterOptions
            // {

            //     SslRedirect = false,
            //      // Require secure connection for dashboard 
            //      RequireSsl = false,
            //      // Case sensitive login checking 
            //      LoginCaseSensitive = false,
            //      // Users 
            //      Users = new[]
            //     {
            //            new BasicAuthAuthorizationUser
            //            {
            //                Login = "admin",//用户名
            //                PasswordClear="admin"
            //                // Password as SHA1 hash 
            //                //Password = new byte[]{ 0x54, ..., 0xa8 }//密码
            //            }
            //     }
            // });
            //var options = new DashboardOptions()
            //{
            //    Authorization = new[] {
            //        filter
            //    }

            //};

            //app.UseHangfireDashboard("/TaskManager", options); //可以改变Dashboard的url
             //app.UseTcpServer();

            #region 添加周期性任务

            //{
            //    //0.读取配置信息
            //    IConfigAppService dbConfig = new ConfigAppService();
            //    var DeleteTxtDays = Convert.ToInt32(dbConfig.GetConfig("DeleteTxtDays").Value);
            //    var DeleteActiveDays = Convert.ToInt32(dbConfig.GetConfig("DeleteActiveDays").Value); 
            //    var DeleteAlarmDays = Convert.ToInt32(dbConfig.GetConfig("DeleteAlarmDays").Value);
            //    var DeleteUploadDays = Convert.ToInt32(dbConfig.GetConfig("DeleteUploadDays").Value);
            //    //1.删除文本日志=30天以前 
            //    RecurringJob.AddOrUpdate(() => Console.WriteLine("DeleteTxtDays"), Cron.Daily(2));//每天凌晨2点执行
            //    //2.删除心跳日志=7天以前
            //    RecurringJob.AddOrUpdate(() => Console.WriteLine("DeleteActiveDays"), Cron.Daily(3));//每天凌晨3点执行
            //    //3.删除报警日志=30天以前
            //    RecurringJob.AddOrUpdate(() => Console.WriteLine("DeleteAlarmDays"), Cron.Daily(4));//每天凌晨4点执行
            //    //4.删除上传日期=7天以前
            //    RecurringJob.AddOrUpdate(() => Console.WriteLine("DeleteUploadDays"), Cron.Daily(5));//每天凌晨5点执行
            //}
            #endregion


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "version:2.5");
                //c.ShowRequestHeaders();
                //c.DocExpansion(DocExpansion.List); 
            });


        }
    }
}
